<template>
  <div class="margin-container-list">
    <!-- 操作区域 -->
    <div class="top-operate">
      <div class="pad-t-15">
        <div class="inline-flex">
          <el-select v-model="textCol" class="width-120">
            <el-option label="仓库名称" value="warehouseName"></el-option>
            <el-option label="仓库编码" value="warehouseCode"></el-option>
          </el-select>
          <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
        </div>
        <el-select v-model="searchListQuery.warehouseType" placeholder="仓库类型" clearable class="mar-l-10"
          style="width: 150px">
          <el-option v-for="(val, key) in dict.warehouseType" :key="key" :label="val" :value="key"></el-option>
        </el-select>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="doSearch">查询</el-button>
          <el-button plain @click="doResetSearch">重置</el-button>
        </el-button-group>
        <div class="pad-t-10">
          <el-button type="primary" @click="doAdd">添加仓库</el-button>
        </div>
      </div>
    </div>
    <!-- 内容列表 -->
    <div class="table-container">
      <el-table :data="dataList" v-loading="listLoading" element-loading-text="加载中">
        <el-table-column type="index" width="60px"></el-table-column>
        <el-table-column label="仓库名称" min-width="220px" prop="warehouseName">
          <template slot-scope="scope">
            <span>{{ scope.row.warehouseName }}</span>
            <br>
            <span class="font-blue">[{{ dict.warehouseType[scope.row.warehouseType] }}]</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库编码" min-width="180px" prop="warehouseCode"></el-table-column>
        <el-table-column label="售后仓" min-width="160px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.afterSaleWarehouseFlag == 1 ? '普通仓' : '售后仓' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库地址" min-width="280px" prop="warehouseDetailAddress"></el-table-column>
        <el-table-column label="管理员" min-width="160px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.realName }}</span>
            <br>
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="140px" prop="status" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.status == 1 ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="330px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="doEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="medium" @click="doLinkAuthorizeGoods(scope.row)">授权商品</el-button>
            <el-button type="text" size="medium" v-if="scope.row.warehouseType == '2'" @click="doSync(scope.row)">同步云仓
            </el-button>
            <el-button type="text" size="medium" v-if="scope.$index != 0 || searchListQuery.currentPage > 1"
              @click="doMove(scope.row, 'up')">上移</el-button>
            <el-button type="text" size="medium"
              v-if="(scope.$index + 1) + ((searchListQuery.currentPage - 1) * searchListQuery.size) < total"
              @click="doMove(scope.row, 'down')">下移</el-button>
            <el-button type="text" size="medium" @click="doDelete(scope.row)">删除</el-button>
            <div v-if="scope.row.warehouseType !== 4">
              <el-button type="text" size="medium" @click="setDefaultExpressOutlets(scope.row)">默认快递网点
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 设置默认网点dialog -->
    <el-dialog title="设置默认网点" :visible.sync="defaultOutletsVisible" :close-on-press-escape="true" width="800px">
      <el-tabs v-model="defaultPlatformType" @tab-click="doChangeTab()">
        <el-tab-pane label="快递鸟面单" name="999"></el-tab-pane>
        <el-tab-pane label="抖音面单" name="1"></el-tab-pane>
        <el-tab-pane label="淘宝菜鸟面单" name="3"></el-tab-pane>
        <el-tab-pane label="拼多多面单" name="4"></el-tab-pane>
      </el-tabs>
      <el-form :model="defaultExpressOutletsEntity" label-position="right" label-width="80px" class="pad-30">
        <el-form-item label="添加网点:">
          <div>
            <el-select v-model="defaultExpressOutletsEntity.enterpriseExpressId" @change="defaultExpressChange()" placeholder="请选择快递公司" style="width: 150px;">
              <el-option v-for="(val, key) in expressOutletsSelectList"
                :key="key"
                :label="val.enterpriseExpressOutletsList[0].expressName"
                :value="val.enterpriseExpressOutletsList[0].enterpriseExpressId">
              </el-option>
            </el-select>
            <el-select v-if="defaultPlatformType != '999'" v-model="defaultExpressOutletsEntity.shopId" @change="shopChange()" placeholder="请选择店铺" style="width: 150px;">
              <el-option v-for="item in defaultShopList" :key="item.shopId" :label="item.shopName" :value="item.shopId"/>
            </el-select>
            <el-select v-model="defaultExpressOutletsEntity.expressOutletsId" placeholder="请选择网点" style="width: 150px;">
              <el-option v-for="(val, key) in outletsList" :key="key" :label="val.sendName"
                :value="val.enterpriseExpressOutletsId" />
            </el-select>
            <el-button type="primary" @click="enableExpressOutlets()">添加</el-button>
          </div>
          <!-- 表格 -->
          <div>
            <el-table ref="multipleTable" :data="defaultExpressOutletsList" v-loading="listOutletsLoading"
              element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header"
              row-class-name="default-row">
              <el-table-column width="180px" label="快递公司" prop="expressName" align="left">
                <template slot-scope="scope">
                  {{scope.row.expressName}}
                </template>
              </el-table-column>
              <el-table-column width="100px" label="店铺">
                <template slot-scope="scope">
                  {{ scope.row.shopName ? scope.row.shopName : '-' }}
                </template>
              </el-table-column>
              <el-table-column width="150px" label="网点" prop="expressType">
                <template slot-scope="scope">
                  <div>{{ scope.row.sendName }}</div>
                  <div>代码：{{ scope.row.sendSite }}</div>
                </template>
              </el-table-column>
              <el-table-column min-width="200px" label="操作" align="right" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="medium" @click="deleteWarehouseExpressOutlets(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="defaultOutletsVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 设置默认网点dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="warehouseVisible" width="650px" @closed="doCloseDialog">
      <div v-loading="dialogLoading" element-loading-text="加载中">
        <div class="scroll-layer-box mar-b-20">
          <el-form ref="warehouseForm" :model="warehouseForm" :rules="rules" label-width="160px"
            class="mar-l-20 mar-r-30">
            <template v-if="warehouseForm.warehouseId != ''">
              <el-form-item label="仓库归属：" style="background: aliceblue;">
                <span>{{ warehouseForm.warehouseSource == '1' ? '总部' : warehouseForm.supplierName }}</span>
                <span>（{{ dict.warehouseSource[warehouseForm.warehouseSource] }}）</span>
              </el-form-item>
            </template>
            <el-form-item label="仓库名称：" prop="warehouseName">
              <el-input v-model="warehouseForm.warehouseName" placeholder="请输入仓库名称"></el-input>
            </el-form-item>
            <el-form-item label="仓库编码：" prop="warehouseCode">
              <el-input v-model="warehouseForm.warehouseCode" placeholder="请输入仓库编码"></el-input>
            </el-form-item>
            <el-form-item label="仓库类型：" prop="warehouseType">
              <el-select v-model="warehouseForm.warehouseType" placeholder="请选择仓库类型"
                :disabled="warehouseForm.warehouseId != ''" @change="doChangeWarehouseType">
                <el-option v-for="(val, key) in dict.warehouseType" :key="key" :label="val" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="warehouseType" v-if="warehouseForm.warehouseType !== '4'">
              <el-checkbox v-model="afterSaleWarehouseFlag">售后仓
              </el-checkbox>
            </el-form-item>
            <el-form-item label="操作员姓名：" prop="realName">
              <el-input v-model="warehouseForm.realName" placeholder="请输入操作员姓名"></el-input>
            </el-form-item>
            <el-form-item label="登录手机号：" prop="phone">
              <el-input v-model="warehouseForm.phone" maxlength="11" :disabled="warehouseForm.warehouseId != ''"
                placeholder="请输入手机号" oninput="this.value=this.value.replace(/^[0,2,3,4,5,6,7,8,9]*$/gi,'')"
                onkeyup="this.value=this.value.replace(/\D/g,'')">
              </el-input>
            </el-form-item>
            <el-form-item label="所属角色：" prop="subRoleId">
              <el-select v-model="warehouseForm.subRoleId" placeholder="请选择角色">
                <el-option v-for="(item, index) in subRoleList" :key="item.subRoleId" :index="index" :label="item.name"
                  :value="item.subRoleId" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态：">
              <el-radio-group v-model="warehouseForm.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="仓库地址：" prop="warehouseArea">
              <el-select class="width-125" v-model="warehouseForm.warehouseProvinceCode" placeholder="请选择省份" clearable
                @change="changeCity(warehouseForm.warehouseProvinceCode)">
                <el-option v-for="item in provinceList" :key="item.areaCode" :label="item.areaName"
                  :value="item.areaCode">
                </el-option>
              </el-select>
              <el-select class="width-125" v-model="warehouseForm.warehouseCityCode" placeholder="请选择城市" clearable
                @change="changeDistrict(warehouseForm.warehouseCityCode)">
                <el-option v-for="item in cityList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                </el-option>
              </el-select>
              <el-select class="width-125" v-model="warehouseForm.warehouseDistrictCode" placeholder="请选择区县" clearable>
                <el-option v-for="item in districtList" :key="item.areaCode" :label="item.areaName"
                  :value="item.areaCode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址：" prop="warehouseAddress">
              <el-input v-model="warehouseForm.warehouseAddress" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <el-form-item label="联系人：">
              <el-input v-model="warehouseForm.contact" placeholder="请输入联系人姓名"></el-input>
            </el-form-item>
            <el-form-item label="联系电话：">
              <el-input v-model="warehouseForm.contactPhone" placeholder="请输入联系电话" maxlength="11"
                oninput="this.value=this.value.replace(/^[0,2,3,4,5,6,7,8,9]*$/gi,'')"
                onkeyup="this.value=this.value.replace(/\D/g,'')"></el-input>
            </el-form-item>
            <div v-show="warehouseForm.warehouseType == '2'">
              <el-form-item label="货主编码：" prop="ownerCode">
                <el-input v-model="warehouseForm.ownerCode" placeholder="请输入货主编码"></el-input>
              </el-form-item>
              <el-form-item label="奇门仓AppKey：" prop="qimenAppKey">
                <el-input v-model="warehouseForm.qimenAppKey" placeholder="请输入奇门仓AppKey"></el-input>
              </el-form-item>
              <el-form-item label="customerId：" prop="qimenCustomerId">
                <el-input v-model="warehouseForm.qimenCustomerId" placeholder="请输入奇门三方客户id"></el-input>
              </el-form-item>
            </div>
            <div v-if="warehouseForm.warehouseType.startsWith('third-')">
              <el-form-item label="第三方仓AppId：" prop="thirdAppId">
                <el-input v-model="warehouseForm.thirdAppId" placeholder="请输入第三方仓AppId"></el-input>
              </el-form-item>
              <el-form-item label="第三方仓AppCode：" prop="thirdAppCode">
                <el-input v-model="warehouseForm.thirdAppCode" placeholder="请输入第三方仓AppCode"></el-input>
              </el-form-item>
              <el-form-item label="第三方仓接口地址：" prop="thirdAppUrl">
                <el-input v-model="warehouseForm.thirdAppUrl" placeholder="请输入第三方仓接口地址"></el-input>
              </el-form-item>
            </div>
            <div v-if="warehouseForm.warehouseType === '4'">
              <el-form-item label="对接系统：" prop="dockingSystemConfigId">
                <el-select v-model="warehouseForm.dockingSystemConfigId" placeholder="请选择对接系统"
                  :disabled="warehouseForm.warehouseId != ''">
                  <el-option v-for="(item) in dockingSystemData" :key="item.configId" :label="item.name"
                    :value="item.configId" />
                </el-select>

              </el-form-item>
              <el-form-item label="海关类别：" prop="customsCategoryId">
                <el-select v-model="warehouseForm.customsCategoryId" placeholder="请选择海关类别">
                  <el-option v-for="(item) in customsCategoryData" :key="item.categoryId" :label="item.categoryName"
                    :value="item.categoryId" />
                </el-select>
              </el-form-item>
              <el-form-item label="检验检疫代码：" prop="inspectionAndQuarantineCodes">
                <el-input v-model="warehouseForm.inspectionAndQuarantineCodes" placeholder="请输入检验检疫代码"></el-input>
              </el-form-item>
              <el-form-item label="主管海关代码：" prop="competentCustomsCode">
                <el-input v-model="warehouseForm.competentCustomsCode" placeholder="请输入主管海关代码"></el-input>
              </el-form-item>
              <el-form-item label="">
                <div class="mar-t-10">
                  <el-checkbox v-model="warehouseForm.isEnableAutoSyncExternalStockFlag" class="mar-r-5"></el-checkbox>
                  启用每<el-input v-model="warehouseForm.autoSyncExternalStockTime" placeholder="请输入时间"
                    style="width: 120px;text-align: center;" class="mar-l-5 mar-r-5" maxlength="4"
                    oninput="this.value=this.value.replace(/\D/g,'')" onkeyup="this.value=this.value.replace(/\D/g,'')"
                    :disabled="!warehouseForm.isEnableAutoSyncExternalStockFlag"></el-input>分钟自动同步外仓库存功能
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doSave">保存</el-button>
        <el-button @click="warehouseVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getNameByPath
  } from '@/utils/get-name-by-path'
  import {
    listEnterpeiseRole
  } from '@/api/system/role'
  import {
    listProvince,
    listCity,
    listDistrict
  } from '@/api/area/area'
  import {
    pagingWarehouse,
    getWarehouse,
    saveWarehouse,
    doSyncQimenWarehouse,
    doMoveUpdate,
    deleteWarehouse,
    listWarehouseType
  } from '@/api/warehouse/warehouseInfo'
  import {
    listAllExpressOutlets
  } from '@/api/goods/expressOutlets'
  import {
    saveWarehouseExpressOutlets,
    listWarehouseOutlets,
    deleteWarehouseExpressOutlets
  } from '@/api/warehouse/warehouseDefaultExpressOutlets'
  import {
    getDockingSystemList
  } from '@/api/system/dockingSystemConfig'
  import {
    getCustomsCategoryList
  } from '@/api/system/customsCategory'
  import { getVillageSupplier } from '@/api/user/supplier'
  export default {
    name: getNameByPath(),
    data() {
      const validateWarehouseArea = (rule, value, callback) => {
        if (!this.warehouseForm.warehouseProvinceCode) {
          callback(new Error('请选择省份'))
        }
        if (!this.warehouseForm.warehouseCityCode) {
          callback(new Error('请选择城市'))
        }
        if (!this.warehouseForm.warehouseDistrictCode) {
          callback(new Error('请选择地区'))
        }
        callback()
      }
      return {
        // 文本model
        textCol: 'warehouseName',
        textValue: '',
        // 查询条件
        searchListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          supplierId: '',
          warehouseSource: '',
          warehouseType: ''
        },
        // 仓库表单
        warehouseForm: {
          warehouseId: '',
          enterpriseId: '',
          realName: '',
          phone: '',
          subRoleId: '',
          status: '1',
          warehouseName: '',
          warehouseCode: '',
          warehouseType: '1',
          warehouseSource: '',
          supplierId: '',
          supplierName: '',
          warehouseProvinceCode: '',
          warehouseCityCode: '',
          warehouseDistrictCode: '',
          warehouseAddress: '',
          contact: '',
          contactPhone: '',
          ownerCode: '',
          qimenAppKey: '',
          qimenCustomerId: '',
          thirdAppId: '',
          thirdAppCode: '',
          thirdAppUrl: '',
          dockingSystemConfigId: '',
          isEnableAutoSyncExternalStockFlag: false,
          isEnableAutoSyncExternalStock: '0',
          autoSyncExternalStockTime: '10',
          customsCategoryId: '',
          inspectionAndQuarantineCodes: '',
          competentCustomsCode: ''
        },
        // 表单规则
        rules: {
          warehouseName: [{
            required: true,
            message: '请输入仓库名称',
            trigger: 'blur'
          }],
          warehouseCode: [{
            max: 50,
            message: '不能超过50个字符',
            trigger: 'blur'
          }],
          warehouseType: [{
            required: true,
            message: '请选择仓库类型',
            trigger: 'blur'
          }],
          realName: [{
            required: true,
            message: '请输入管理员姓名',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '请输入登录手机号',
            trigger: 'blur'
          }],
          subRoleId: [{
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }],
          warehouseArea: [{
            required: true,
            validator: validateWarehouseArea,
            trigger: 'blur'
          }],
          warehouseAddress: [{
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }],
          dockingSystemConfigId: [{
            required: true,
            message: '请选择对接系统',
            trigger: 'change'
          }],
          customsCategoryId: [{
            required: true,
            message: '请选择海关类别',
            trigger: 'change'
          }]
        },
        // 数据字典
        dict: {
          warehouseSource: {},
          warehouseType: {}
        },
        // dialog标题
        dialogTitle: '',
        // 省集合
        provinceList: [],
        // 市集合
        cityList: [],
        // 区集合
        districtList: [],
        // 角色集合
        subRoleList: [],
        listLoading: false,
        dialogLoading: false,
        warehouseVisible: false,
        total: 0,
        dataList: [],
        warehouseTypeMap: {},
        afterSaleWarehouseFlag: false,
        defaultOutletsVisible: false,
        defaultPlatformType: '999',
        // 快递网点默认实体
        defaultExpressOutletsEntity: {
          enterpriseExpressId: '',
          warehouseId: '',
          platformType: '',
          shopId: '',
          expressOutletsId: ''
        },
        defaultExpressOutletsList: [],
        expressOutletsSelectList: [],
        outletsList: [],
        defaultShopList: [],
        listOutletsLoading: false,
        // 对接系统数据
        dockingSystemData: [],
        // 海关类别数据
        customsCategoryData: [],
        // 面单使用数据类型：1-企业数据；2-供应商数据
        kuaiDiNiaoUseType: '',
        taoBaoUseType: '',
        douYinUseType: '',
        pinDuoDuoUseType: ''
      }
    },
    // 初始化页面
    created() {
      // 获取企业仓库角色
      listEnterpeiseRole({
        enterpriseId: this.getEnterpriseId(),
        warehouseFlag: 1
      }).then(response => {
        this.subRoleList = response.data
      })
      listProvince().then(response => {
        this.provinceList = response.data
      })
      listWarehouseType({
        enterpriseId: this.getEnterpriseId()
      }).then(response => {
        if (response.isError) return
        const warehouseTypeList = response.data
        const warehouseTypeDict = this.dict.warehouseType

        warehouseTypeList.forEach(warehouseType => {
          const key = 'third-' + warehouseType.warehouseTypeId
          warehouseTypeDict[key] = '第三方仓-' + warehouseType.warehouseTypeName
          this.warehouseTypeMap[key] = warehouseType
        })
      })
      const dockingSystemParams = {
        systemBusinessType: 1
      }
      getDockingSystemList(dockingSystemParams).then(response => {
        this.dockingSystemData = response.data
      })
      getCustomsCategoryList({}).then(response => {
        this.customsCategoryData = response.data
      })
      this.initList()
    },
    methods: {
      // 初始化
      initList() {
        this.listLoading = true
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.supplierId = this.getSupplierId()
        this.searchListQuery.warehouseSource = this.getSupplierId() ? 2 : 1
        if (this.searchListQuery.warehouseType.startsWith('third-')) {
          this.searchListQuery.warehouseTypeId = this.searchListQuery.warehouseType.substr('third-'.length)
        } else {
          this.searchListQuery.warehouseTypeId = ''
        }
        pagingWarehouse(this.searchListQuery).then(response => {
          this.listLoading = false
          this.dataList = response.data.records
          // 第三方仓数据字典处理
          this.dataList.forEach(warehouse => {
            if (warehouse.warehouseType === 3) {
              warehouse.warehouseType = 'third-' + warehouse.warehouseTypeId
            }
          })
          this.total = response.data.total
          const warehouseTypeDict = this.dict.warehouseType
          Object.assign(this.dict, response.data.dict)
          if (warehouseTypeDict) {
            Object.assign(this.dict.warehouseType, warehouseTypeDict)
          }
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.searchListQuery = originData.searchListQuery
        this.doSearch()
      },
      // 仓库类型切换事件
      doChangeWarehouseType(val) {
        if (val === '1') {
          this.warehouseForm.ownerCode = ''
          this.warehouseForm.qimenAppKey = ''
          this.warehouseForm.qimenCustomerId = ''
          this.thirdAppId = ''
          this.thirdAppCode = ''
          this.thirdAppUrl = ''
        }
        if (val === '2') {
          this.thirdAppId = ''
          this.thirdAppCode = ''
          this.thirdAppUrl = ''
        }
        if (val.startsWith('third-')) {
          this.warehouseForm.ownerCode = ''
          this.warehouseForm.qimenAppKey = ''
          this.warehouseForm.qimenCustomerId = ''
        }
        this.$nextTick(() => {
          this.$refs['warehouseForm'].clearValidate()
        })
      },
      // 获取地址-市
      changeCity(provinceCode, cityCode, districtCode) {
        this.cityList = []
        this.districtList = []
        this.warehouseForm.warehouseCityCode = ''
        this.warehouseForm.warehouseDistrictCode = ''
        if (provinceCode) {
          listCity(provinceCode).then(response => {
            this.cityList = response.data
          })
          this.warehouseForm.warehouseCityCode = cityCode
          this.changeDistrict(cityCode, districtCode)
        }
      },
      // 获取地址-区
      changeDistrict(cityCode, districtCode) {
        this.districtList = []
        this.warehouseForm.warehouseDistrictCode = ''
        if (cityCode) {
          listDistrict(cityCode).then(response => {
            this.districtList = response.data
          })
          this.warehouseForm.warehouseDistrictCode = districtCode
        }
      },
      // 添加事件
      doAdd() {
        this.dialogTitle = '添加仓库'
        this.warehouseVisible = true
      },
      // 保存事件
      doSave() {
        this.$refs['warehouseForm'].validate((valid) => {
          if (valid) {
            this.dialogLoading = true
            this.warehouseForm.afterSaleWarehouseFlag = this.afterSaleWarehouseFlag ? 2 : 1
            this.warehouseForm.isEnableAutoSyncExternalStock = this.warehouseForm
              .isEnableAutoSyncExternalStockFlag ? 1 : 0
            this.warehouseForm.enterpriseId = this.getEnterpriseId()
            const data = Object.assign({}, this.warehouseForm)
            data.enterpriseId = this.getEnterpriseId()
            if (this.getSupplierId()) {
              data.warehouseSource = 2
              data.supplierId = this.getSupplierId()
            } else {
              data.warehouseSource = 1
            }
            // 保税仓类型的校验
            if (data.warehouseType === '4') {
              this.warehouseForm.afterSaleWarehouseFlag = 1
              if (this.warehouseForm.isEnableAutoSyncExternalStockFlag) {
                if (!this.warehouseForm.autoSyncExternalStockTime) {
                  this.dialogLoading = false
                  this.msgError('请输入自动同步时间')
                  return
                }
                if (this.warehouseForm.autoSyncExternalStockTime < 5) {
                  this.dialogLoading = false
                  this.msgError('自动同步时间不能小于5分钟')
                  return
                }
              }
              var customsCategoryCode = ''
              this.customsCategoryData.forEach((item) => {
                if (item.categoryId === this.warehouseForm.customsCategoryId) {
                  customsCategoryCode = item.categoryCode
                  return
                }
              })
              // 广州电子口岸3.0 (总署版) 该类型，需要校验另外2个字段
              if (customsCategoryCode === 'HG018') {
                if (!this.warehouseForm.inspectionAndQuarantineCodes) {
                  this.dialogLoading = false
                  this.msgError('请填写检验检疫代码')
                  return
                }
                if (!this.warehouseForm.competentCustomsCode) {
                  this.dialogLoading = false
                  this.msgError('请填写主管海关代码')
                  return
                }
              }
            }
            if (data.warehouseType.startsWith('third-')) {
              if (!data.thirdAppId) {
                this.dialogLoading = false
                this.$message.error('第三方仓AppId不能为空')
                return
              }
              if (!data.thirdAppCode) {
                this.dialogLoading = false
                this.$message.error('第三方仓AppCode不能为空')
                return
              }
              const warehouseType = this.warehouseTypeMap[this.warehouseForm.warehouseType]
              // 第三方仓，保存到数据库需要分开存储类型和类型id
              data.warehouseType = 3
              data.warehouseTypeId = warehouseType.warehouseTypeId
            }
            saveWarehouse(data).then(response => {
              this.dialogLoading = false
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '保存成功'
              })
              this.warehouseVisible = false
              this.initList()
            })
          }
        })
      },
      // 编辑事件
      doEdit(row) {
        this.listLoading = true
        getWarehouse(row.warehouseId).then((response) => {
          this.listLoading = false
          if (response.isError) return
          this.warehouseForm = response.data
          this.warehouseForm.status = this.warehouseForm.status.toString()
          this.warehouseForm.warehouseSource = this.warehouseForm.warehouseSource.toString()
          this.warehouseForm.warehouseType = this.warehouseForm.warehouseType.toString()
          if (this.warehouseForm.warehouseType === '3') {
            this.warehouseForm.warehouseType = 'third-' + this.warehouseForm.warehouseTypeId
          }
          this.changeCity(this.warehouseForm.warehouseProvinceCode, this.warehouseForm.warehouseCityCode, this
            .warehouseForm.warehouseDistrictCode)
          this.dialogTitle = '编辑仓库'
          this.warehouseVisible = true
          // 售后仓
          this.afterSaleWarehouseFlag = this.warehouseForm.afterSaleWarehouseFlag === 2
          // 是否启用自动同步外部仓库库存
          this.$set(this.warehouseForm, 'isEnableAutoSyncExternalStockFlag', this.warehouseForm
            .isEnableAutoSyncExternalStock === 1)
          if (!this.warehouseForm.autoSyncExternalStockTime) {
            this.$set(this.warehouseForm, 'autoSyncExternalStockTime', 5)
          }
          this.warehouseForm.crossBorderDockingType = this.warehouseForm.crossBorderDockingType ? this.warehouseForm
            .crossBorderDockingType.toString() : '1'
        })
      },
      // dialog关闭事件
      doCloseDialog() {
        const originData = this.$options.data()
        this.warehouseForm = originData.warehouseForm
        this.$nextTick(() => {
          this.$refs['warehouseForm'].clearValidate()
        })
      },
      // 授权商品事件
      doLinkAuthorizeGoods(row) {
        this.$router.push({
          path: '/warehouse/warehouse-authorize-goods/index',
          query: {
            warehouseId: row.warehouseId,
            authorizeType: row.authorizeType
          }
        })
      },
      // 同步云仓事件
      doSync(row) {
        this.listLoading = true
        doSyncQimenWarehouse({
          warehouseId: row.warehouseId
        }).then((response) => {
          this.listLoading = false
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '同步成功'
          })
        })
      },
      // 排序移动事件
      doMove(row, moveType) {
        const form = {
          warehouseId: row.warehouseId,
          moveType: moveType
        }
        this.listLoading = true
        doMoveUpdate(form).then((response) => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.initList()
        })
      },
      // 删除事件
      doDelete(row) {
        this.$confirm('仓库删除后无法恢复，确定要删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          deleteWarehouse({
            warehouseId: row.warehouseId
          }).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.initList()
          })
        }).catch(() => {})
      },
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 平台切换
      doChangeTab() {
        this.clearDefaultParams()
        const warehouseId = this.defaultExpressOutletsEntity.warehouseId
        this.listAllExpressOutlets()
        this.listWarehouseOutlets(warehouseId, this.defaultPlatformType)
      },
      // 清除设置默认网点数据
      clearDefaultParams() {
        this.defaultExpressOutletsEntity.enterpriseExpressId = ''
        this.defaultExpressOutletsEntity.shopId = ''
        this.defaultExpressOutletsEntity.expressOutletsId = ''
        this.expressOutletsSelectList = []
        this.defaultShopList = []
        this.outletsList = []
      },
      // 设置默认网点
      setDefaultExpressOutlets(row) {
        this.clearDefaultParams()
        this.defaultOutletsVisible = true
        this.defaultExpressOutletsEntity.warehouseId = row.warehouseId
        this.defaultPlatformType = '999'
        const villageSupplierFx = new Promise((resolve, reject) => {
          if (this.getSupplierId()) {
            getVillageSupplier(this.getSupplierId()).then(response => {
              if (response.isError) return
              this.kuaiDiNiaoUseType = response.data.kuaiDiNiaoUseType
              this.taoBaoUseType = response.data.taoBaoUseType
              this.douYinUseType = response.data.douYinUseType
              this.pinDuoDuoUseType = response.data.pinDuoDuoUseType
              resolve('success')
            })
          } else {
            resolve('success')
          }
        })
        villageSupplierFx.then((result) => {
          if (result === 'success') {
            this.listAllExpressOutlets()
            this.listWarehouseOutlets(row.warehouseId, this.defaultPlatformType)
          }
        })
      },
      // 查询网点列表
      listAllExpressOutlets() {
        const platformType = this.defaultPlatformType
        const searchParams = {
          enterpriseId: this.getEnterpriseId(),
          platformType: platformType,
          supplierId: this.getSupplierId()
        }
        if ((platformType === '999' && this.kuaiDiNiaoUseType === 1) || (platformType === '1' && this.douYinUseType === 1) ||
              (platformType === '3' && this.taoBaoUseType === 1) || (platformType === '4' && this.pinDuoDuoUseType === 1)) {
          searchParams.supplierId = ''
        }
        listAllExpressOutlets(searchParams).then(response => {
          if (response.isError) return
          this.expressOutletsSelectList = response.data
        })
      },
      // 默认网点设置快递选择事件
      defaultExpressChange() {
        const enterpriseExpressId = this.defaultExpressOutletsEntity.enterpriseExpressId
        if (this.expressOutletsSelectList && enterpriseExpressId) {
          this.defaultExpressOutletsEntity.expressOutletsId = ''
          this.defaultExpressOutletsEntity.shopId = ''
          this.expressOutletsSelectList.forEach(e => {
            if (e.enterpriseExpressId === enterpriseExpressId) {
              const outletsList = e.enterpriseExpressOutletsList
              this.outletsList = outletsList
              const shopList = []
              const shopIdArr = []
              outletsList.forEach(o => {
                if (shopIdArr.indexOf(o.shopId) < 0) {
                  shopList.push({
                    shopId: o.shopId,
                    shopName: o.shopName
                  })
                  shopIdArr.push(o.shopId)
                }
              })
              this.defaultShopList = shopList
            }
          })
        }
      },
      // 默认网点店铺选择事件
      shopChange() {
        const enterpriseExpressId = this.defaultExpressOutletsEntity.enterpriseExpressId
        const shopId = this.defaultExpressOutletsEntity.shopId
        if (this.expressOutletsSelectList && enterpriseExpressId) {
          this.defaultExpressOutletsEntity.expressOutletsId = ''
          this.expressOutletsSelectList.forEach(e => {
            if (e.enterpriseExpressId === enterpriseExpressId) {
              const outletsList = e.enterpriseExpressOutletsList
              const defaultOutlets = []
              outletsList.forEach(o => {
                if (shopId === o.shopId) {
                  defaultOutlets.push(o)
                }
              })
              this.outletsList = defaultOutlets
            }
          })
        }
      },
      // 查询仓库默认网点
      listWarehouseOutlets(warehouseId, platformType) {
        this.listOutletsLoading = true
        const params = {
          platformType: platformType,
          warehouseId: warehouseId,
          source: 1
        }
        if ((platformType === '999' && this.kuaiDiNiaoUseType === 2) || (platformType === '1' && this.douYinUseType === 2) ||
              (platformType === '3' && this.taoBaoUseType === 2) || (platformType === '4' && this.pinDuoDuoUseType === 2)) {
          params.source = 2
        }
        listWarehouseOutlets(params).then(response => {
          if (response.isError) return
          this.defaultExpressOutletsList = response.data
          this.listOutletsLoading = false
        })
      },
      // 添加企业默认网点
      enableExpressOutlets() {
        const enterpriseExpressId = this.defaultExpressOutletsEntity.enterpriseExpressId
        const shopId = this.defaultExpressOutletsEntity.shopId
        const expressOutletsId = this.defaultExpressOutletsEntity.expressOutletsId
        const warehouseId = this.defaultExpressOutletsEntity.warehouseId
        if (!enterpriseExpressId) {
          this.$message({ type: 'error', message: '请选择快递公司！' })
          return
        }
        if (!expressOutletsId) {
          this.$message({ type: 'error', message: '请选择网点！' })
          return
        }
        if (this.defaultPlatformType !== '999' && !shopId) {
          this.$message({ type: 'error', message: '请选择店铺！' })
          return
        }
        const params = {
          warehouseId: warehouseId,
          platformType: this.defaultPlatformType,
          enterpriseExpressOutletsId: expressOutletsId,
          enterpriseExpressId: enterpriseExpressId
        }
        saveWarehouseExpressOutlets(params).then(response => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '添加成功！'
          })
          this.listOutletsLoading = true
          this.defaultExpressOutletsEntity.enterpriseExpressId = ''
          this.defaultExpressOutletsEntity.shopId = ''
          this.defaultExpressOutletsEntity.expressOutletsId = ''
          this.defaultShopList = []
          this.outletsList = []
          this.listWarehouseOutlets(warehouseId, this.defaultPlatformType)
        })
      },
      // 移除仓库网点
      deleteWarehouseExpressOutlets(row) {
        const warehouseId = this.defaultExpressOutletsEntity.warehouseId
        deleteWarehouseExpressOutlets({
          warehouseId: warehouseId,
          enterpriseExpressOutletsId: row.enterpriseExpressOutletsId
        }).then(response => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '移除成功！'
          })
          this.listOutletsLoading = true
          this.defaultExpressOutletsEntity.enterpriseExpressId = ''
          this.defaultExpressOutletsEntity.shopId = ''
          this.defaultExpressOutletsEntity.expressOutletsId = ''
          this.defaultShopList = []
          this.outletsList = []
          this.listWarehouseOutlets(warehouseId, this.defaultPlatformType)
        })
      }
    }
  }
</script>

<style scoped>

</style>
